<template>
  <div class="repayment-plan">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>还款计划管理</h3>
          <div class="header-actions">
            <!-- 隐藏这两个按钮 -->
            <!-- <el-button type="primary" @click="handleGeneratePlan">生成还款计划</el-button>
            <el-button type="primary" @click="handleBatchGenerate">批量生成</el-button> -->
            <el-button type="success" @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>

      <!-- 统计卡片 -->
      <div class="statistics-cards" v-if="statistics">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card shadow="hover">
              <div class="statistic-item">
                <div class="statistic-title">今日到期</div>
                <div class="statistic-value">{{ statistics.todayDue.count }}笔 / {{ statistics.todayDue.amount }}元</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover">
              <div class="statistic-item">
                <div class="statistic-title">本周到期</div>
                <div class="statistic-value">{{ statistics.weekDue.count }}笔 / {{ statistics.weekDue.amount }}元</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover">
              <div class="statistic-item">
                <div class="statistic-title">逾期情况</div>
                <div class="statistic-value">{{ statistics.overdue.count }}笔 / {{ statistics.overdue.amount }}元</div>
                <div class="statistic-extra">逾期率: {{ statistics.overdue.ratio }}</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="合同编号">
          <el-input v-model="searchForm.contractNo" placeholder="请输入合同编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="贷款编号">
          <el-select 
            v-model="searchForm.loanNo" 
            placeholder="请选择贷款编号" 
            clearable 
            filterable 
            style="width: 220px;"
            :remote="true"
            :remote-method="handleLoanNoSearch"
            :loading="loanNoLoading"
          >
            <el-option
              v-for="item in loanOptions"
              :key="item.loanNo"
              :label="`${item.loanNo} - ${item.customerName || '未知'}`"
              :value="item.loanNo"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-select 
            v-model="searchForm.customerName" 
            placeholder="请选择客户" 
            clearable 
            filterable 
            style="width: 180px;"
            :remote="true"
            :remote-method="handleCustomerSearch"
            :loading="customerLoading"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.customerName"
              :value="item.customerName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="还款状态">
          <el-select v-model="searchForm.repayStatus" placeholder="请选择还款状态" clearable style="width: 150px;">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%" v-loading="loading" row-key="planId">
        <!-- 使用与后端数据匹配的静态列 -->
        <el-table-column prop="planId" label="计划ID" width="80"></el-table-column>
        <el-table-column prop="contractId" label="合同ID" width="80"></el-table-column>
        <el-table-column prop="termNo" label="期数" width="60"></el-table-column>
        <el-table-column prop="repayDate" label="应还日期" width="110"></el-table-column>
        <el-table-column prop="principal" label="应还本金" width="110">
          <template #default="scope">
            {{ formatMoney(scope.row.principal) }}
          </template>
        </el-table-column>
        <el-table-column prop="interest" label="应还利息" width="110">
          <template #default="scope">
            {{ formatMoney(scope.row.interest) }}
          </template>
        </el-table-column>
        <el-table-column prop="repayAmount" label="应还总额" width="110">
          <template #default="scope">
            {{ formatMoney(scope.row.repayAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="principalBalance" label="剩余本金" width="110">
          <template #default="scope">
            {{ formatMoney(scope.row.principalBalance) }}
          </template>
        </el-table-column>
        <el-table-column prop="repayStatus" label="状态" width="90">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.repayStatus)">
              {{ 
                scope.row.repayStatus === 10 ? '待还款' : 
                scope.row.repayStatus === 20 ? '已还款' : 
                scope.row.repayStatus === 30 ? '逾期' : '未知' 
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150"></el-table-column>
        <el-table-column prop="remark" label="备注" min-width="120"></el-table-column>
        
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleViewPlan(scope.row)">查看计划</el-button>
            <el-button link type="primary" @click="handleEarlyRepay(scope.row)" 
                       :disabled="scope.row.repayStatus === 20">提前还款</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 生成还款计划对话框 -->
    <el-dialog v-model="generatePlanDialogVisible" title="生成还款计划" width="600px">
      <el-form :model="planForm" label-width="120px">
        <el-form-item label="贷款编号" required>
          <el-select v-model="planForm.loanNo" placeholder="请选择贷款" filterable style="width: 100%"
            @change="handleLoanSelected">
            <el-option
              v-for="item in loanOptions"
              :key="item.loanNo"
              :label="`${item.loanNo} - ${item.customerName || '未知'}`"
              :value="item.loanNo"
            >
              <div style="display: flex; justify-content: space-between">
                <span>{{ item.loanNo }}</span>
                <span>{{ item.customerName || '未知客户' }} ({{ formatMoney(item.loanAmount) }})</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="还款方式" required>
          <el-select v-model="planForm.repaymentMethod" placeholder="请选择还款方式" style="width: 100%">
            <el-option label="等额本息" value="equal_installment"></el-option>
            <el-option label="等额本金" value="equal_principal"></el-option>
            <el-option label="先息后本" value="interest_first"></el-option>
            <el-option label="到期一次性还本付息" value="maturity"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="还款日" required>
          <el-input-number v-model="planForm.repaymentDay" :min="1" :max="28" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="首次还款日期" required>
          <el-date-picker v-model="planForm.firstRepaymentDate" type="date" placeholder="选择首次还款日期" style="width: 100%"></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="generatePlanDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitGeneratePlan">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 还款对话框 -->
    <el-dialog v-model="repayDialogVisible" title="还款" width="500px">
      <el-form :model="repayForm" label-width="120px">
        <el-form-item label="贷款编号">
          <el-input v-model="repayForm.loanNo" disabled></el-input>
        </el-form-item>
        <el-form-item label="期数">
          <el-input v-model="repayForm.period" disabled></el-input>
        </el-form-item>
        <el-form-item label="应还日期">
          <el-input v-model="repayForm.dueDate" disabled></el-input>
        </el-form-item>
        <el-form-item label="应还金额">
          <el-input v-model="repayForm.amount" disabled></el-input>
        </el-form-item>
        <el-form-item label="实际还款日期" required>
          <el-date-picker v-model="repayForm.payDate" type="date" placeholder="选择还款日期" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="实际还款金额" required>
          <el-input-number v-model="repayForm.payAmount" :precision="2" :min="0" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="还款方式" required>
          <el-select v-model="repayForm.payMethod" placeholder="请选择还款方式" style="width: 100%">
            <el-option
              v-for="item in paymentMethodOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交易流水号">
          <el-input v-model="repayForm.transactionNo" placeholder="请输入交易流水号"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="repayForm.remark" type="textarea" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="repayDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRepay">确认还款</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看还款计划对话框 -->
    <el-dialog v-model="viewPlanDialogVisible" title="还款计划详情" width="800px">
      <div class="plan-detail">
        <div class="plan-header">
          <div class="header-left">
            <h4>基本信息</h4>
            <p><label>合同编号:</label> {{ currentPlan.contractNo }}</p>
            <p><label>贷款编号:</label> {{ currentPlan.loanNo }}</p>
            <p><label>客户姓名:</label> {{ currentPlan.customerName }}</p>
            <p><label>联系电话:</label> {{ currentPlan.customerPhone }}</p>
          </div>
          <div class="header-right">
            <p><label>贷款金额:</label> {{ formatMoney(currentPlan.loanAmount) }}</p>
            <p><label>贷款期限:</label> {{ currentPlan.loanTerm }}月</p>
            <p><label>年利率:</label> {{ currentPlan.interestRate }}%</p>
            <p><label>还款方式:</label> {{ currentPlan.repaymentMethod }}</p>
          </div>
        </div>
        
        <div class="plan-summary">
          <h4>还款概况</h4>
          <div class="summary-row">
            <div class="summary-item">
              <span class="item-label">总期数</span>
              <span class="item-value">{{ currentPlan.totalPeriods }}</span>
            </div>
            <div class="summary-item">
              <span class="item-label">已还期数</span>
              <span class="item-value">{{ currentPlan.paidPeriods }}</span>
            </div>
            <div class="summary-item">
              <span class="item-label">总金额</span>
              <span class="item-value">{{ formatMoney(currentPlan.totalAmount) }}</span>
            </div>
            <div class="summary-item">
              <span class="item-label">已还金额</span>
              <span class="item-value">{{ formatMoney(currentPlan.paidAmount) }}</span>
            </div>
            <div class="summary-item">
              <span class="item-label">剩余金额</span>
              <span class="item-value">{{ formatMoney(currentPlan.remainingAmount) }}</span>
            </div>
          </div>
        </div>
        
        <div class="plan-installments">
          <h4>还款计划明细</h4>
          <el-table :data="currentPlan.installments || []" border style="width: 100%">
            <el-table-column prop="period" label="期数" width="60"></el-table-column>
            <el-table-column prop="dueDate" label="应还日期" width="100"></el-table-column>
            <el-table-column prop="principal" label="应还本金" width="120">
              <template #default="scope">{{ formatMoney(scope.row.principal) }}</template>
            </el-table-column>
            <el-table-column prop="interest" label="应还利息" width="120">
              <template #default="scope">{{ formatMoney(scope.row.interest) }}</template>
            </el-table-column>
            <el-table-column prop="amount" label="应还总额" width="120">
              <template #default="scope">{{ formatMoney(scope.row.amount) }}</template>
            </el-table-column>
            <el-table-column prop="principalBalance" label="剩余本金" width="120">
              <template #default="scope">{{ formatMoney(scope.row.principalBalance) }}</template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getInstallmentStatusType(scope.row.status)">{{ scope.row.statusName }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="payDate" label="实际还款日期" width="100"></el-table-column>
            <el-table-column prop="payAmount" label="实际还款金额" width="120">
              <template #default="scope">{{ scope.row.payAmount ? formatMoney(scope.row.payAmount) : '-' }}</template>
            </el-table-column>
          </el-table>
        </div>
        
        <div v-if="currentPlan.payRecords && currentPlan.payRecords.length > 0" class="plan-records">
          <h4>还款记录</h4>
          <el-table :data="currentPlan.payRecords" border style="width: 100%">
            <el-table-column prop="payDate" label="还款日期" width="100"></el-table-column>
            <el-table-column prop="payAmount" label="还款金额" width="120">
              <template #default="scope">{{ formatMoney(scope.row.payAmount) }}</template>
            </el-table-column>
            <el-table-column prop="principal" label="本金" width="120">
              <template #default="scope">{{ formatMoney(scope.row.principal) }}</template>
            </el-table-column>
            <el-table-column prop="interest" label="利息" width="120">
              <template #default="scope">{{ formatMoney(scope.row.interest) }}</template>
            </el-table-column>
            <el-table-column prop="penalty" label="罚息" width="100">
              <template #default="scope">{{ formatMoney(scope.row.penalty) }}</template>
            </el-table-column>
            <el-table-column prop="payMethodName" label="还款方式" width="100"></el-table-column>
            <el-table-column prop="transactionNo" label="交易流水号" width="140"></el-table-column>
            <el-table-column prop="operator" label="操作人" width="100"></el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewPlanDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleExportDetail(currentPlan)">导出明细</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 提前还款对话框 -->
    <el-dialog v-model="earlyRepayDialogVisible" title="提前还款" width="500px">
      <el-form :model="earlyRepayForm" label-width="120px">
        <el-form-item label="剩余本金">
          <el-input v-model="earlyRepayForm.payAmount" disabled></el-input>
        </el-form-item>
        <el-form-item label="优惠金额">
          <el-input-number v-model="earlyRepayForm.discount" :precision="2" :min="0" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="实际还款金额">
          <el-input-number 
            v-model="earlyRepayForm.payAmount" 
            :precision="2" 
            :min="0" 
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="还款日期" required>
          <el-date-picker v-model="earlyRepayForm.payDate" type="date" placeholder="选择还款日期" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="还款方式" required>
          <el-select v-model="earlyRepayForm.payMethod" placeholder="请选择还款方式" style="width: 100%">
            <el-option
              v-for="item in paymentMethodOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交易流水号">
          <el-input v-model="earlyRepayForm.transactionNo" placeholder="请输入交易流水号"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="earlyRepayForm.remark" type="textarea" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="earlyRepayDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEarlyRepay">确认还款</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 调整还款计划对话框 -->
    <el-dialog v-model="adjustPlanDialogVisible" title="调整还款计划" width="900px">
      <el-form :model="adjustPlanForm" label-width="100px">
        <el-form-item label="调整原因" required>
          <el-input v-model="adjustPlanForm.reason" type="textarea" rows="2"></el-input>
        </el-form-item>
        
        <div class="adjust-table">
          <h4>调整明细</h4>
          <el-table :data="adjustPlanForm.adjustments" border style="width: 100%">
            <el-table-column prop="period" label="期数" width="80"></el-table-column>
            <el-table-column label="应还日期" width="220">
              <template #default="scope">
                <el-date-picker 
                  v-model="scope.row.dueDate" 
                  type="date" 
                  placeholder="选择日期"
                  style="width: 100%"
                ></el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="应还本金" width="180">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.principal" 
                  :precision="2" 
                  :min="0"
                  style="width: 100%"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="应还利息" width="180">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.interest" 
                  :precision="2" 
                  :min="0"
                  style="width: 100%"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="合计" width="120">
              <template #default="scope">
                {{ formatMoney(scope.row.principal + scope.row.interest) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <el-form-item label="附件" class="attach-field">
          <el-upload
            :limit="5"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleAttachmentChange"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adjustPlanDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdjust">确认调整</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 罚息计算对话框 -->
    <el-dialog v-model="penaltyDialogVisible" title="罚息计算" width="500px">
      <el-form :model="penaltyForm" label-width="100px">
        <el-form-item label="逾期天数">
          <el-tag type="danger" size="large" class="overdue-days">{{ penaltyForm.overdueDays }}天</el-tag>
        </el-form-item>
        <el-form-item label="应还本金">
          <el-input v-model="penaltyForm.principal" disabled></el-input>
        </el-form-item>
        <el-form-item label="应还利息">
          <el-input v-model="penaltyForm.interest" disabled></el-input>
        </el-form-item>
        <el-form-item label="应还总额">
          <el-input v-model="penaltyForm.amount" disabled></el-input>
        </el-form-item>
        <el-form-item label="罚息率">
          <el-input v-model="penaltyForm.penaltyRate" disabled>
            <template #append>‰/天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="罚息金额">
          <el-input v-model="penaltyForm.penalty" disabled></el-input>
        </el-form-item>
        <div class="total-amount">
          <span class="label">总计应还:</span>
          <span class="value">{{ formatMoney(penaltyForm.totalAmount) }}</span>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="penaltyDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleRepayWithPenalty">前往还款</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { repaymentPlanApi, repaymentRecordApi } from '@/api/repayment'

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 统计数据
const statistics = ref(null)

// 搜索表单
const searchForm = reactive({
  contractNo: '',
  loanNo: '',
  customerName: '',
  repayStatus: '',
  startDate: '',
  endDate: ''
})

// 存储原始响应
const rawResponse = ref(null)

// 日期范围
const dateRange = ref([])

// 选项数据
const loanOptions = ref([])
const customerOptions = ref([])
const statusOptions = ref([])
const paymentMethodOptions = ref([])

// 加载状态
const loanNoLoading = ref(false)
const customerLoading = ref(false)

// 生成还款计划对话框
const generatePlanDialogVisible = ref(false)
const planForm = reactive({
  contractId: null,
  loanNo: '',
  repaymentMethod: 'equal_installment',
  repaymentDay: 1,
  firstRepaymentDate: ''
})

// 还款对话框
const repayDialogVisible = ref(false)
const repayForm = reactive({
  planId: null,
  installmentId: null,
  loanNo: '',
  period: '',
  dueDate: '',
  amount: 0,
  payDate: new Date(),
  payAmount: 0,
  payMethod: 'bank_transfer',
  remark: ''
})

// 详情对话框数据
const currentPlan = ref({})
const viewPlanDialogVisible = ref(false)

// 提前还款对话框
const earlyRepayDialogVisible = ref(false)
const earlyRepayForm = reactive({
  planId: null,
  payDate: new Date(),
  payAmount: 0,
  discount: 0,
  payMethod: 'bank_transfer',
  remark: ''
})

// 调整还款计划对话框
const adjustPlanDialogVisible = ref(false)
const adjustPlanForm = reactive({
  planId: null,
  adjustments: [],
  reason: '',
  attachmentUrls: []
})

// 罚息计算对话框
const penaltyDialogVisible = ref(false)
const penaltyForm = reactive({
  installmentId: null,
  overdueDays: 0,
  principal: 0,
  interest: 0,
  amount: 0,
  penaltyRate: 0,
  penalty: 0,
  totalAmount: 0
})

// 表格列配置
const columns = ref([
  { prop: 'planId', label: '计划ID', width: 100 },
  { prop: 'termNo', label: '期数', width: 80 },
  { prop: 'repayDate', label: '应还款日期', width: 120 },
  { prop: 'principal', label: '本金', width: 120, formatter: (row) => formatMoney(row.principal) },
  { prop: 'interest', label: '利息', width: 120, formatter: (row) => formatMoney(row.interest) },
  { prop: 'repayAmount', label: '应还总额', width: 120, formatter: (row) => formatMoney(row.repayAmount) },
  { prop: 'principalBalance', label: '剩余本金', width: 120, formatter: (row) => formatMoney(row.principalBalance) },
  { 
    prop: 'repayStatus', 
    label: '还款状态', 
    width: 100,
    formatter: (row) => {
      const statusMap = {
        10: '未还款',
        20: '已还款',
        30: '逾期'
      }
      return statusMap[row.repayStatus] || `未知(${row.repayStatus})`
    }
  },
  { prop: 'createTime', label: '创建时间', width: 160 },
  { prop: 'remark', label: '备注', width: 160 }
])

// 初始化数据
onMounted(() => {
  console.log('页面初始化')
  console.log('表格列配置:', columns.value)
  
  // 先获取选项值
  Promise.all([
    getStatusOptions(),
    getPaymentMethodOptions()
  ]).then(() => {
    console.log('选项数据加载完成')
    console.log('还款状态选项:', statusOptions.value)
    console.log('支付方式选项:', paymentMethodOptions.value)
  }).catch(err => {
    console.error('加载选项数据出错:', err)
  })
  
  // 获取列表数据
  getList().then(() => {
    console.log('初始数据加载完成')
  }).catch(err => {
    console.error('初始数据加载出错:', err)
  })
  
  // 获取统计数据
  getStatistics().then(() => {
    console.log('统计数据加载完成')
  }).catch(err => {
    console.error('统计数据加载出错:', err)
  })
})

// 获取还款计划列表
const getList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    console.log('查询参数:', params)
    const res = await repaymentPlanApi.getList(params)
    console.log('API返回数据:', res)
    
    // 保存原始响应
    rawResponse.value = res
    
    if (res.code === "200" || res.code === 200) { // 注意：后端返回的code可能是字符串
      // 检查返回的数据结构
      console.log('返回数据结构类型:', typeof res.data)
      
      if (res.data && res.data.records && Array.isArray(res.data.records)) {
        // 直接使用返回的records数据
        tableData.value = res.data.records
        
        // 更新分页信息
        total.value = res.data.total || 0;
        currentPage.value = res.data.current || 1;
        pageSize.value = res.data.size || 10;
        
        console.log('加载表格数据成功，共', tableData.value.length, '条记录')
        
        // 如果没有数据，给用户提示
        if (tableData.value.length === 0) {
          ElMessage.info('没有找到符合条件的数据')
        }
      } else {
        console.error('数据格式不符合预期:', res.data)
        tableData.value = []
        total.value = 0
        ElMessage.warning('返回的数据格式不符合预期')
      }
      
      return Promise.resolve(tableData.value);
    } else {
      console.error('请求返回错误:', res.msg || '未知错误')
      tableData.value = []
      total.value = 0
      ElMessage.error(res.msg || '获取数据失败')
      return Promise.reject(new Error(res.msg || '获取数据失败'));
    }
  } catch (error) {
    console.error('获取还款计划列表失败:', error)
    tableData.value = []
    total.value = 0
    ElMessage.error('获取数据失败')
    return Promise.reject(error);
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getStatistics = async () => {
  // try {
  //   const res = await repaymentPlanApi.getStatistics()
  //   if (res.code === 200) {
  //     statistics.value = res.data
  //     return Promise.resolve(res.data);
  //   }
  //   return Promise.reject(new Error(res.msg || '获取统计数据失败'));
  // } catch (error) {
  //   console.error('获取统计数据失败:', error)
  //   return Promise.reject(error);
  // }
}

// 获取还款状态选项
const getStatusOptions = async () => {
  try {
    const res = await repaymentPlanApi.getRepayStatuses()
    if (res.code === 200) {
      statusOptions.value = res.data
      return Promise.resolve(res.data);
    }
    // API请求不成功，添加默认选项
    setDefaultStatusOptions()
    return Promise.reject(new Error(res.msg || '获取状态选项失败'));
  } catch (error) {
    console.error('获取还款状态选项失败:', error)
    // 设置默认状态选项
    setDefaultStatusOptions()
    return Promise.reject(error);
  }
}

// 设置默认状态选项
const setDefaultStatusOptions = () => {
  statusOptions.value = [
    { value: '10', label: '待还款' },
    { value: '20', label: '已还款' },
    { value: '30', label: '逾期' },
    { value: '40', label: '提前还款' },
    { value: '50', label: '部分还款' },
    { value: '60', label: '展期' }
  ]
}

// 获取还款方式选项
const getPaymentMethodOptions = async () => {
  // try {
  //   const res = await repaymentPlanApi.getPaymentMethods()
  //   if (res.code === 200) {
  //     paymentMethodOptions.value = res.data
  //     return Promise.resolve(res.data);
  //   }
  //   return Promise.reject(new Error(res.msg || '获取支付方式选项失败'));
  // } catch (error) {
  //   console.error('获取还款方式选项失败:', error)
  //   return Promise.reject(error);
  // }
}

// 生成还款计划
const handleGeneratePlan = () => {
  planForm.loanNo = ''
  planForm.repaymentMethod = 'equal_installment'
  planForm.repaymentDay = 1
  planForm.firstRepaymentDate = ''
  generatePlanDialogVisible.value = true
  // 获取贷款选项
  loadInitialLoanOptions()
}

// 加载初始贷款选项
const loadInitialLoanOptions = async () => {
  loanNoLoading.value = true
  try {
    // 使用新接口获取已批准的贷款列表
    const res = await repaymentPlanApi.getApprovedLoans({
      pageNum: 1,
      pageSize: 10,
      loanNo: '',
      customerName: '',
      loanType: '',
      status: 'approved'
    })
    
    if (res.code === 200 || res.code === "200") {
      // 根据新的数据结构，从list中提取贷款选项
      if (res.data && res.data.list && Array.isArray(res.data.list)) {
        loanOptions.value = res.data.list.map(item => ({
          id: item.id,
          loanNo: item.loanNo,
          customerName: item.customerName || '未知客户',
          loanAmount: item.loanAmount || 0
        }))
      } else {
        // 如果数据为空，提供一些示例数据
        provideSampleLoanOptions()
      }
    } else {
      // 如果API请求返回错误，提供示例数据
      provideSampleLoanOptions()
    }
  } catch (error) {
    console.error('加载贷款选项失败:', error)
    // 发生错误时提供示例数据
    provideSampleLoanOptions()
  } finally {
    loanNoLoading.value = false
  }
}

// 提供示例贷款选项数据
const provideSampleLoanOptions = () => {
  loanOptions.value = [
    { id: 30001, loanNo: 'DK202403010001', customerName: '张三', loanAmount: 100000 },
    { id: 30002, loanNo: 'DK202403010002', customerName: '李四', loanAmount: 200000 },
    { id: 30003, loanNo: 'DK202403010003', customerName: '王五', loanAmount: 150000 },
    { id: 30004, loanNo: 'DK202403010004', customerName: '赵六', loanAmount: 300000 },
    { id: 30005, loanNo: 'DK202403010005', customerName: '钱七', loanAmount: 120000 }
  ]
}

// 搜索贷款编号
const handleLoanNoSearch = async (query) => {
  if (query.length < 2) return
  loanNoLoading.value = true
  try {
    // 使用新接口搜索贷款
    const res = await repaymentPlanApi.getApprovedLoans({
      pageNum: 1,
      pageSize: 10,
      loanNo: query,
      customerName: '',
      loanType: '',
      status: 'approved'
    })
    
    if (res.code === 200 || res.code === "200") {
      // 从新的数据结构中提取贷款选项
      if (res.data && res.data.list && Array.isArray(res.data.list)) {
        loanOptions.value = res.data.list.map(item => ({
          id: item.id,
          loanNo: item.loanNo,
          customerName: item.customerName || '未知客户',
          loanAmount: item.loanAmount || 0
        }))
      }
    }
  } catch (error) {
    console.error('搜索贷款编号失败:', error)
  } finally {
    loanNoLoading.value = false
  }
}

// 搜索客户
const handleCustomerSearch = async (query) => {
  if (query.length < 2) return
  customerLoading.value = true
  try {
    // 使用搜索客户名的新接口，通过API搜索客户
    const res = await repaymentPlanApi.getApprovedLoans({
      pageNum: 1,
      pageSize: 10,
      loanNo: '',
      customerName: query,
      loanType: '',
      status: 'approved'
    })
    
    if (res.code === 200 || res.code === "200") {
      if (res.data && res.data.list && Array.isArray(res.data.list)) {
        // 提取客户信息，去重
        const customerMap = new Map();
        res.data.list.forEach(item => {
          if (item.customerName) {
            customerMap.set(item.customerName, {
              id: item.id,
              customerName: item.customerName
            });
          }
        });
        
        customerOptions.value = Array.from(customerMap.values());
      }
    }
  } catch (error) {
    console.error('搜索客户失败:', error)
  } finally {
    customerLoading.value = false
  }
}

// 处理日期范围变化
const handleDateRangeChange = (val) => {
  if (val) {
    searchForm.startDate = val[0]
    searchForm.endDate = val[1]
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
}

// 执行搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.contractNo = ''
  searchForm.loanNo = ''
  searchForm.customerName = ''
  searchForm.repayStatus = ''
  searchForm.startDate = ''
  searchForm.endDate = ''
  dateRange.value = []
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

// 提交生成还款计划
const submitGeneratePlan = async () => {
  if (!planForm.loanNo) {
    ElMessage.warning('请选择贷款')
    return
  }
  
  try {
    const data = {
      contractId: planForm.contractId // 这里使用的是从loanNo中获取的id值
    }
    console.log('生成还款计划参数:', data)
    const res = await repaymentPlanApi.generate(data)
    if (res.code === 200) {
      ElMessage.success('生成还款计划成功')
      generatePlanDialogVisible.value = false
      getList()
    } else {
      ElMessage.error(res.msg || '生成还款计划失败')
    }
  } catch (error) {
    console.error('生成还款计划失败:', error)
    ElMessage.error('操作失败')
  }
}

// 批量生成还款计划
const handleBatchGenerate = () => {
  ElMessageBox.prompt('请输入要批量生成还款计划的合同ID，多个ID用逗号分隔', '批量生成', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^(\d+,)*\d+$/,
    inputErrorMessage: '请输入正确的合同ID格式(如: 1,2,3)'
  }).then(({ value }) => {
    const contractIds = value.split(',').map(id => parseInt(id.trim()))
    batchGeneratePlans(contractIds)
  }).catch(() => {
    // 取消操作
  })
}

// 批量生成
const batchGeneratePlans = async (contractIds) => {
  try {
    const res = await repaymentPlanApi.batchGenerate({ contractIds })
    if (res.code === 200) {
      ElMessage.success(`批量生成成功: ${res.data.successCount}个，失败: ${res.data.failCount}个`)
      getList()
    } else {
      ElMessage.error(res.msg || '批量生成失败')
    }
  } catch (error) {
    console.error('批量生成还款计划失败:', error)
    ElMessage.error('操作失败')
  }
}

// 查看还款计划
const handleViewPlan = async (row) => {
  try {
    const res = await repaymentPlanApi.getPlanDetail(row.planId)
    if (res.code === 200 || res.code === "200") {
      // 使用后端返回的数据，并处理可能缺失的字段
      const planData = res.data;
      
      // 临时设置一些可能缺失的字段
      const contractNo = planData.contractNo || `HT${row.contractId}` || '未知';
      const loanNo = planData.loanNo || `DK${row.contractId}` || '未知';
      const customerName = planData.customerName || '未知客户';
      
      currentPlan.value = {
        ...planData,
        // 确保基础信息字段存在
        contractNo: contractNo,
        loanNo: loanNo, 
        customerName: customerName,
        customerPhone: planData.customerPhone || '未知',
        loanAmount: planData.loanAmount || row.principalBalance || 0,
        loanTerm: planData.loanTerm || 12,
        interestRate: planData.interestRate || 4.35,
        repaymentMethod: planData.repaymentMethod || '等额本息',
        
        // 确保统计信息字段存在
        totalPeriods: planData.totalPeriods || 12,
        paidPeriods: planData.paidPeriods || 0,
        totalAmount: planData.totalAmount || 0,
        paidAmount: planData.paidAmount || 0,
        remainingAmount: planData.remainingAmount || row.principalBalance || 0,
        
        // 处理分期数据
        installments: Array.isArray(planData.installments) 
          ? planData.installments.map(item => ({
              ...item,
              statusName: item.repayStatus === 10 ? '待还款' : 
                         item.repayStatus === 20 ? '已还款' : 
                         item.repayStatus === 30 ? '逾期' : '未知'
            }))
          : [{ // 如果没有分期数据，创建一个基于当前行的默认分期
              termNo: row.termNo,
              period: row.termNo,
              dueDate: row.repayDate,
              principal: row.principal,
              interest: row.interest,
              amount: row.repayAmount,
              principalBalance: row.principalBalance,
              status: row.repayStatus,
              statusName: row.repayStatus === 10 ? '待还款' : 
                          row.repayStatus === 20 ? '已还款' : 
                          row.repayStatus === 30 ? '逾期' : '未知'
            }]
      }
      
      viewPlanDialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取还款计划详情失败')
    }
  } catch (error) {
    console.error('获取还款计划详情失败:', error)
    ElMessage.error('操作失败')
  }
}

// 调整还款计划
const handleAdjust = (row) => {
  // 确保有planId
  if (!row.planId) {
    ElMessage.error('无法获取计划ID')
    return
  }
  
  adjustPlanForm.planId = row.planId
  // 初始化调整表单
  loadInstallmentsForAdjust(row.planId)
  adjustPlanDialogVisible.value = true
}

// 加载分期信息用于调整
const loadInstallmentsForAdjust = async (planId) => {
  try {
    const res = await repaymentPlanApi.getPlanDetail(planId)
    if (res.code === 200) {
      // 只加载未还款的分期（状态为10或30的记录）
      const unpaidInstallments = (res.data.installments || []).filter(item => item.repayStatus !== 20)
      adjustPlanForm.adjustments = unpaidInstallments.map(item => ({
        termNo: item.termNo,
        period: item.termNo,
        repayDate: item.repayDate,
        principal: item.principal,
        interest: item.interest
      }))
    }
  } catch (error) {
    console.error('加载分期信息失败:', error)
    ElMessage.error('加载分期信息失败')
  }
}

// 提交调整
const submitAdjust = async () => {
  if (!adjustPlanForm.reason) {
    ElMessage.warning('请填写调整原因')
    return
  }
  
  try {
    const res = await repaymentPlanApi.adjustPlan(adjustPlanForm)
    if (res.code === 200) {
      ElMessage.success('调整还款计划成功')
      adjustPlanDialogVisible.value = false
      getList()
    } else {
      ElMessage.error(res.msg || '调整还款计划失败')
    }
  } catch (error) {
    console.error('调整还款计划失败:', error)
    ElMessage.error('操作失败')
  }
}

// 还款
const handleRepay = (plan, installment) => {
  repayForm.planId = plan.planId
  repayForm.installmentId = installment.termNo // 使用termNo作为installmentId
  repayForm.loanNo = plan.loanNo || ''
  repayForm.period = installment.termNo
  repayForm.dueDate = installment.repayDate
  repayForm.amount = installment.repayAmount
  repayForm.payDate = new Date()
  repayForm.payAmount = installment.repayAmount
  repayForm.payMethod = 'bank_transfer'
  repayForm.remark = ''
  
  repayDialogVisible.value = true
}

// 提交还款
const submitRepay = async () => {
  // 这里假设使用还款记录API进行还款，实际可能需要根据具体接口调整
  try {
    const data = {
      ...repayForm
    }
    const res = await repaymentRecordApi.add(data)
    if (res.code === 200) {
      ElMessage.success('还款成功')
      repayDialogVisible.value = false
      getList()
    } else {
      ElMessage.error(res.msg || '还款失败')
    }
  } catch (error) {
    console.error('还款失败:', error)
    ElMessage.error('操作失败')
  }
}

// 提前还款
const handleEarlyRepay = (row) => {
  // 确保有planId
  if (!row.planId) {
    ElMessage.error('无法获取计划ID')
    return
  }
  
  earlyRepayForm.planId = row.planId
  earlyRepayForm.payDate = new Date()
  earlyRepayForm.payAmount = row.principalBalance || 0
  earlyRepayForm.discount = 0
  earlyRepayForm.payMethod = 'bank_transfer'
  earlyRepayForm.remark = '提前还款'
  
  earlyRepayDialogVisible.value = true
}

// 提交提前还款
const submitEarlyRepay = async () => {
  // 这里假设使用还款记录API进行提前还款，实际可能需要根据具体接口调整
  try {
    const data = {
      ...earlyRepayForm,
      isEarlyRepay: true
    }
    const res = await repaymentRecordApi.add(data)
    if (res.code === 200) {
      ElMessage.success('提前还款成功')
      earlyRepayDialogVisible.value = false
      getList()
    } else {
      ElMessage.error(res.msg || '提前还款失败')
    }
  } catch (error) {
    console.error('提前还款失败:', error)
    ElMessage.error('操作失败')
  }
}

// 计算罚息
const handleCalculatePenalty = async (installment) => {
  try {
    // 这里假设通过计算罚息的API，需要提供安装ID和其他相关信息
    const data = {
      planId: installment.planId,
      termNo: installment.termNo,
      principal: installment.principal,
      interest: installment.interest,
      repayDate: installment.repayDate,
      overdueDays: installment.overdueDays || 0
    }
    
    const res = await repaymentPlanApi.calculatePenalty(data)
    if (res.code === 200) {
      penaltyForm.installmentId = installment.termNo
      penaltyForm.overdueDays = res.data.overdueDays || installment.overdueDays || 0
      penaltyForm.principal = installment.principal
      penaltyForm.interest = installment.interest
      penaltyForm.amount = installment.repayAmount
      penaltyForm.penaltyRate = res.data.penaltyRate || 0
      penaltyForm.penalty = res.data.penalty || 0
      penaltyForm.totalAmount = res.data.totalAmount || installment.repayAmount + (res.data.penalty || 0)
      
      penaltyDialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '计算罚息失败')
    }
  } catch (error) {
    console.error('计算罚息失败:', error)
    ElMessage.error('操作失败')
  }
}

// 导出
const handleExport = () => {
  const params = { ...searchForm }
  
  // 使用浏览器下载
  const downloadFile = (data, filename) => {
    const blob = new Blob([data])
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = filename
    link.click()
    URL.revokeObjectURL(link.href)
  }
  
  repaymentPlanApi.exportPlan(params).then(res => {
    downloadFile(res, `还款计划_${new Date().getTime()}.xlsx`)
  }).catch(error => {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  })
}

// 导出明细
const handleExportDetail = (row) => {
  // 使用planId导出，不依赖row.id
  const planId = row.planId || row.id
  
  if (!planId) {
    ElMessage.error('无法获取计划ID')
    return
  }
  
  repaymentPlanApi.exportPlanDetail(planId).then(res => {
    const downloadFile = (data, filename) => {
      const blob = new Blob([data])
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = filename
      link.click()
      URL.revokeObjectURL(link.href)
    }
    
    // 生成文件名，使用合同ID或计划ID
    const contractIdStr = row.contractId ? `_${row.contractId}` : ''
    const loanNoStr = row.loanNo || `计划${row.planId}`
    
    downloadFile(res, `还款计划明细${contractIdStr}_${loanNoStr}_${new Date().getTime()}.xlsx`)
  }).catch(error => {
    console.error('导出明细失败:', error)
    ElMessage.error('导出明细失败')
  })
}

// 查看详情
const handleDetail = (plan, installment) => {
  // 可以根据需要实现详情查看功能
  ElMessage.info('查看分期详情: ' + installment.period)
}

// 格式化金额
const formatMoney = (amount) => {
  // 检查是否为空值
  if (amount === null || amount === undefined) return '-'
  
  // 转换为数字
  const num = parseFloat(amount)
  
  // 检查是否为有效数字
  if (isNaN(num)) return '-'
  
  // 使用toLocaleString格式化数字
  try {
    return num.toLocaleString('zh-CN', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    }) + '元'
  } catch (e) {
    console.error('格式化金额出错:', e, amount)
    // 备用格式化方法
    return num.toFixed(2) + '元'
  }
}

// 获取还款状态类型
const getInstallmentStatusType = (status) => {
  const map = {
    10: 'info',    // 待还款
    20: 'success', // 已还款
    30: 'danger'   // 逾期
  }
  return map[status] || 'info';
}

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    10: 'info',    // 待还款
    20: 'success', // 已还款
    30: 'danger'   // 逾期
  }
  return map[status] || 'info';
}

// 处理贷款选择
const handleLoanSelected = (value) => {
  // 找到对应的贷款选项
  const selected = loanOptions.value.find(item => item.loanNo === value)
  if (selected) {
    planForm.contractId = selected.id  // 设置合同ID
    console.log(`已选择贷款: ${value}, 设置contractId为: ${selected.id}`)
  }
}

// 处理附件变更
const handleAttachmentChange = (file, fileList) => {
  // 这里可以处理上传文件的逻辑，比如将文件上传到服务器后获取URL
  console.log('文件变更:', file)
}

// 带罚息的还款
const handleRepayWithPenalty = () => {
  // 关闭当前对话框
  penaltyDialogVisible.value = false
  
  // 获取相关分期信息
  // 注意：这里需要有获取分期信息的方法，或者在计算罚息时已经保存了分期信息
  // 打开还款对话框
  repayForm.installmentId = penaltyForm.installmentId
  repayForm.payAmount = penaltyForm.totalAmount
  repayForm.remark = `逾期${penaltyForm.overdueDays}天，含罚息${penaltyForm.penalty}元`
  
  repayDialogVisible.value = true
}

// 加载还款计划明细
const loadPlanInstallments = async (plan) => {
  try {
    // 如果已经加载过则不再重复加载
    if (plan.installmentsLoaded) return;
    
    console.log('加载计划明细, planId:', plan.planId)
    
    // 尝试从API获取详细数据
    try {
      const res = await repaymentPlanApi.getPlanDetail(plan.planId)
      if ((res.code === 200 || res.code === "200") && res.data && res.data.installments) {
        plan.installments = res.data.installments
        plan.installmentsLoaded = true
        return
      }
    } catch (err) {
      console.error('API获取分期数据失败:', err)
    }
    
    // 如果API获取失败，直接使用当前行作为唯一的明细
    plan.installments = [{
      termNo: plan.termNo,
      repayDate: plan.repayDate,
      principal: plan.principal,
      interest: plan.interest,
      repayAmount: plan.repayAmount,
      principalBalance: plan.principalBalance,
      repayStatus: plan.repayStatus
    }]
    
    console.log('设置的installments:', plan.installments)
    
    // 标记已加载
    plan.installmentsLoaded = true
  } catch (error) {
    console.error('加载还款计划明细失败:', error)
    // 创建一个模拟的明细数据，确保UI显示不会出错
    plan.installments = [{
      termNo: plan.termNo || 1,
      repayDate: plan.repayDate || new Date().toISOString().split('T')[0],
      principal: plan.principal || 0,
      interest: plan.interest || 0,
      repayAmount: plan.repayAmount || 0,
      principalBalance: plan.principalBalance || 0,
      repayStatus: plan.repayStatus || 10,
    }]
    plan.installmentsLoaded = true
    ElMessage.error('加载明细数据失败')
  }
}
</script>

<style scoped>
.repayment-plan {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-top: 20px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.statistics-cards {
  margin-bottom: 20px;
}

.statistic-item {
  text-align: center;
  padding: 10px;
}

.statistic-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.statistic-value {
  font-size: 20px;
  color: #409EFF;
  font-weight: bold;
}

.statistic-extra {
  font-size: 14px;
  color: #F56C6C;
  margin-top: 5px;
}

.plan-detail {
  padding: 20px;
}

.plan-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.header-left, .header-right {
  flex: 1;
}

.plan-header h4 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #303133;
}

.plan-header p {
  margin: 5px 0;
}

.plan-header label {
  font-weight: bold;
  margin-right: 5px;
}

.plan-summary {
  margin-bottom: 20px;
}

.plan-summary h4 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #303133;
}

.summary-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.summary-item {
  flex: 1;
  min-width: 120px;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  text-align: center;
}

.item-label {
  display: block;
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.item-value {
  display: block;
  font-size: 16px;
  color: #409EFF;
  font-weight: bold;
}

.plan-installments {
  margin-top: 20px;
}

.plan-installments h4 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #303133;
}

.attach-field {
  margin-top: 20px;
}

.total-amount {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.total-amount .label {
  font-size: 16px;
  color: #303133;
  margin-right: 10px;
}

.total-amount .value {
  font-size: 18px;
  color: #F56C6C;
  font-weight: bold;
}

.overdue-days {
  color: #F56C6C;
  font-weight: bold;
}

.loading-installments {
  display: flex;
  justify-content: center;
  padding: 20px;
}
</style> 